module.exports = function (app, models, $, db, nm) {
  let sql = {
    sort: {
      level: 1,
      sort: -1,
    },
    projection: {
      name: 1,
      sort: 1,
      url: 1,
      parentId: 1,
      level: 1,
      img: 1,
      status: 1,
      id: 1,
    },
  };
  //isonly 只返回已有菜单
  function groupMenuRouter(isonly, req, next) {
    models.group_menu.list({ groupId: req.query.groupId }, (ret) => {
      if (!ret.errorMsg) {
        let groupMenus = {};
        for (let i = 0; i < ret.length; i++)
          groupMenus["_" + ret[i].menuId] = ret[i]._id;
        models.menu.list(
          { unitId: req.unitId, status: 1 },
          (ret) => {
            if (isonly) {
              let rcRet = [];
              if (ret.length) {
                for (let i = 0; i < ret.length; i++) {
                  if (groupMenus["_" + ret[i].id]) rcRet.push(ret[i]);
                }
              }

              next(rcRet);
            } else {
              if (ret.length) {
                for (let i = 0; i < ret.length; i++) {
                  ret[i].status = groupMenus["_" + ret[i].id] ? 1 : 0;
                }
              }
              next(ret);
            }
          },
          sql
        );
      } else {
        next(ret);
      }
    });
  }
  //获取群组下菜单树
  app.get("/v1/groupMenuTree", (req, res) => {
    groupMenuRouter(false, req, (ret) => {
      if (ret.length) ret = $.listToTree(ret);
      res.send(ret);
    });
  });
  //获取左侧菜单
  app.get("/v1/leftMenuTree", (req, res) => {
    groupMenuRouter(true, req, (ret) => {
      if (ret.length) ret = $.listToTree(ret);
      res.send(ret);
    });
  });

  //获取菜单列表
  // app.get('/v1/menu', (req, res) => {
  // 	var query = { unitId:req.unitId }
  // 	if(req.query.pageSize || req.query.pageNum){
  // 		req.query.pageSize = req.query.pageSize || 10
  // 		req.query.pageNum = req.query.pageNum || 1;
  // 	}
  // 	models.menu.list(query, ret => {
  // 		res.send(ret)
  // 	},sql)
  // })
  //获取菜单树
  app.get("/v1/menuTree", (req, res) => {
    models.menu.list(
      { unitId: req.unitId },
      (ret) => {
        res.send($.listToTree(ret));
      },
      sql
    );
  });
  //获取菜单详情
  app.get("/v1/menuInfo", (req, res) => {
    if (req.query.id) {
      models.menu.find({ id: req.query.id }, (ret) => {
        res.send(ret);
      });
    } else {
      res.send({ errorMsg: "请传入菜单ID" });
    }
  });
  //新增菜单
  app.post("/v1/menu", (req, res) => {
    req.body.unitId = req.unitId;
    req.body.parentId = req.body.parentId || 0;
    models.menu.insert(req.body, (ret) => {
      res.send(ret);
    });
  });
  //修改菜单
  app.put("/v1/menu", (req, res) => {
    models.menu.update({ id: req.body.id }, req.body, (ret) => {
      res.send(ret);
    });
  });
  //删除菜单
  app.delete("/v1/menu", (req, res) => {
    models.menu.remove({ id: req.query.id, unitId: req.unitId }, (ret) => {
      res.send(ret);
    });
  });
};
